package com.game.gateway.start;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kodgames.core.event.EventManager;
import com.kodgames.core.event.IEvent;
import com.kodgames.core.event.IEventListener;
import com.game.core.util.PackageScaner;
import com.game.gateway.listener.ListenerAnnotation;

public class EventInitializer
{
	static private Logger logger = LoggerFactory.getLogger(EventInitializer.class);
	private static EventInitializer instance = new EventInitializer();

	private EventInitializer()
	{
	}

	public static EventInitializer getInstance()
	{
		return instance;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public int init()
	{
		try
		{
			List<Map<String, Object>> listtemp = new ArrayList<>();
			List<Class> commonActionClasses = PackageScaner.getClasses("com.game.gateway.listener", ".class", true);
			for (Class listenerClass : commonActionClasses)
			{
				Annotation annotation = listenerClass.getAnnotation(ListenerAnnotation.class);
				if (annotation != null)
				{
					ListenerAnnotation listenerAnnotation = (ListenerAnnotation) annotation;
					Map<String, Object> map = new HashMap<>();
					map.put("level", listenerAnnotation.level());
					map.put("event", listenerAnnotation.eventClass());
					map.put("listener", listenerAnnotation.listenerClass().newInstance());
					listtemp.add(map);
					continue;
				}
				logger.error("Please add ListenerAnnotation for the Listener:{}", listenerClass.getSimpleName());
			}

			Collections.sort(listtemp, new Comparator<Map<String, Object>>()
			{
				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2)
				{
					return (int) o2.get("level") - (int) o1.get("level");
				}
			});
			for (Map<String, Object> map : listtemp)
				EventManager.getInstance().registerListener((Class<? extends IEvent>) map.get("event"), (IEventListener) map.get("listener"));

			return 0;
		}
		catch (Exception e)
		{
			logger.error(e.toString());
		}
		return -1;
	}
}
